<template>
    <div class="app-container">
        <el-row :gutter="20">
            <!--部门数据-->
            <el-col :span="6" :xs="24" :style="{height:'100%'}">
                <div class="head-container" :style="{height:'calc(100% - 52px)', overflow:'auto'}">
                    <el-tree class="tree-dept-border" :data="deptList" :props="defaultProps"
                            :expand-on-click-node="false"
                            :highlight-current="true"
                            :load="loadChildren"
                            @node-click="handleNodeClick"
                            lazy>
                        <span class="custom-tree-node" slot-scope="{ node, data }">
                         <span>
                           {{ data.orgName }}
                         </span>
                        </span>
                    </el-tree>
                </div>
            </el-col>
            <!--用户数据-->
            <el-col :span="18" :xs="24" class="el-border">
                <!-- 搜索栏 -->
                <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
                    <el-form-item label="工号" prop="employeeId">
                        <el-input v-model="queryParams.employeeId" placeholder="请输入工号" clearable size="small"
                                  @keyup.enter.native="handleQuery"/>
                    </el-form-item>
                    <el-form-item label="姓名" prop="employeeName">
                        <el-input v-model="queryParams.employeeName" placeholder="请输入姓名" clearable size="small"
                                  @keyup.enter.native="handleQuery"/>
                    </el-form-item>

                    <el-form-item label="电话" prop="employeeTelephone">
                        <el-input v-model="queryParams.employeeTelephone" placeholder="请输入电话" clearable size="small"
                                  @keyup.enter.native="handleQuery"/>
                    </el-form-item>

                    <el-form-item label="员工标签" prop="employeeTag">
                        <el-select v-model="queryParams.employeeTag" placeholder="员工标签" clearable size="small">
                            <el-option v-for="dict in getEmployeeTagOptions"
                                    :key="dict.code"
                                    :label="dict.name"
                                    :value="dict.code"
                            />
                        </el-select>
                    </el-form-item>

                    <el-form-item label="入职时间">
                        <el-date-picker v-model="dateRange" size="small" style="width: 240px"
                                        value-format="yyyy-MM-dd" type="daterange" range-separator="-"
                                        start-placeholder="开始日期" end-placeholder="结束日期"
                        ></el-date-picker>
                    </el-form-item>
                    <el-form-item style="margin-left: 10px;">
                        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                        <el-button icon="el-icon-refresh" size="mini" style="margin-left: 10px;" @click="resetQuery">重置</el-button>
                    </el-form-item>
                </el-form>

                <!-- 操作 -->
                <el-row :gutter="10" class="mb8">
                    <el-col :span="1.5">
                        <el-button type="primary" icon="el-icon-plus" size="mini" v-hasPermi="['Empolyeectrl:add']"
                                   :disabled="selectedTreeNodes.length === 0 || selectedNode.parentId === '-1'" @click="handleAddUser">
                            新增人员到当前组织
                        </el-button>
                    </el-col>
                    <!--<el-col :span="1.5">
                        <el-button type="danger" icon="el-icon-user" size="mini" :disabled="multiple" v-hasPermi="['Empolyeectrl:move']">
                            批量移动
                        </el-button>
                    </el-col>-->
                    <right-toolbar :showSearch.sync="showSearch"></right-toolbar>
                </el-row>

                <el-alert
                        :title="selectedNode === undefined ? '总共'+ total +'人' : selectedNode.orgName +'：总共' + total +'人'"
                        type="info"
                        :closable="false"
                        show-icon>
                </el-alert>

<!--             max-height="360"   -->
                <el-table v-loading="loading" :row-key="getRowKeys" :data="userList.slice((currentPage-1)*pageSize,currentPage*pageSize)"
                          @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="50" fixed align="center" :reserve-selection="true"/>
                    <el-table-column label="序号" align="center" type="index" fixed :show-overflow-tooltip="false"/>
                    <el-table-column label="工号" align="center" prop="employeeId" fixed :show-overflow-tooltip="true"/>
                    <el-table-column label="用户姓名" align="center" prop="employeeName" :show-overflow-tooltip="true"/>
                    <el-table-column label="性别" align="center" prop="employeeSex"/>
                    <el-table-column label="所属组织" align="center" prop="orgName" :show-overflow-tooltip="true"/>
                    <el-table-column label="标签" align="center" prop="employeeTag" :formatter="getEmployeeTagFormat" :show-overflow-tooltip="true"/>
                    <el-table-column label="电话" align="center" prop="employeeTelephone" :show-overflow-tooltip="true"/>
                    <el-table-column label="岗位" align="center" prop="employeeJob" :show-overflow-tooltip="true"/>
                    <el-table-column label="入职时间" align="center" prop="employeeEntryTime" width="100"/>
                    <el-table-column label="操作" align="center" fixed="right" width="150"
                                     class-name="small-padding fixed-width">
                        <template slot-scope="scope">
                            <el-button size="mini" type="text" icon="el-icon-edit" v-hasPermi="['Empolyeectrl:edit']"
                                       @click="handleUpdateUser(scope.row)">修改
                            </el-button>
                            <!--<el-button size="mini" type="text" icon="el-icon-s-check" v-hasPermi="['Empolyeectrl:move']"
                                       @click="handleMove(scope.row)">移动
                            </el-button>-->
                            <el-button v-if="scope.row.userId !== 1" size="mini" type="text" icon="el-icon-delete" v-hasPermi="['Empolyeectrl:delete']"
                                       @click="onDelete(scope.row)">删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <pagination
                        v-show="userList.length>0"
                        :total="userList.length"
                        :page.sync="currentPage"
                        :limit.sync="pageSize"
                />

                <!-- 添加或修改用户 -->
                <el-dialog :title="title" :visible.sync="open" v-if="open" width="55%" append-to-body>
                    <el-tabs>
                        <user-form :userForm="userForm" @submitForm="getEmployeeList"
                                 @userCallBack="userCallBack"></user-form>
                    </el-tabs>
                </el-dialog>


            </el-col>
        </el-row>

    </div>
</template>

<script>
    import {getUserAuth} from '@/api/platform/account'
    import {deleteorganization, getorganization} from "@/api/organization/organization";
    import {
        getEmployee,
        addEmployee,
        editEmployeeWithFile,
        editEmployee,
        deleteEmployeeTombstone
    } from '@/api/basicdata/employee'
    import "@riophae/vue-treeselect/dist/vue-treeselect.css";
    import Treeselect from "@riophae/vue-treeselect";
    import userForm from "./form/userForm";

    export default {
        name: "index",
        components: {Treeselect, userForm},
        data() {
            return {
                // 组织表格树数据
                deptList: [],
                defaultProps: {
                    children: "children",
                    label: "orgName"
                },
                ids: [],
                maps: new Map(),
                // 查询参数
                queryParams: {
                    employeeId: undefined,
                    employeeName: undefined,
                    employeeTelephone: undefined,
                    employeeTag: undefined
                },
                // 日期范围
                dateRange: [],
                // 用户标签数据字典
                getEmployeeTagOptions: [],
                // 显示搜索条件
                showSearch: true,
                // 角色页面按钮权限
                roleData: {},
                // 用户表格数据
                userList: [],
                // 用户表单
                userForm: {
                    employeeId: undefined,
                    employeeName: undefined,
                    employeeEntryTime: undefined,
                    employeeSex: undefined,
                    scheduleState: undefined,
                    employeeTelephone: undefined,
                    employeeJob: undefined,
                    orgName: undefined,
                    employeeDutyInfo: [], // 工种
                    employeeStatusInfo: {}, //状态
                    organizationId: undefined, // 部门ID
                    id: undefined,
                    employeeCertifyInfo: [] //证书
                },
                // 弹出层标题
                title: "",
                // 是否弹出层
                open: false,
                // 用户数量
                total: 0,
                // 非多个禁用
                multiple: true,
                // 遮罩层
                loading: false,
                // 分页
                currentPage: 1,
                currentIndex: '',
                pageSize: 10,
                selectedTreeNodes: [],
                selectedNode: undefined,


            }
        },
        created() {
            // 查询页面按钮权限
            this.getUserAuthData();
            //查询员工标签字典状态
            this.getDicts("employee_tag").then(response => {
                this.getEmployeeTagOptions = response.responseBody.result;
            });
            //    初始化所有用户列表
            this.getEmployeeList({});
        },
        methods: {
            // 查询页面按钮权限
            getUserAuthData() {
                getUserAuth({
                    'searchParams': {
                        'userCode': this.$store.getters.userCode,
                        'isBlackList': '1'
                    }
                }).then(res => {
                    if (res.retCode === '200') {
                        if (res.responseBody) {
                            this.roleData = res.responseBody
                            // console.log('roledata----', this.roleData)
                        }
                    } else {
                        console.log(res)
                    }
                })
            },

            // 查询父组织列表
            getdatafromback(orgCode) {
                this.deptList = [];
                getorganization({'searchParams': {'orgCode': orgCode}}).then(res => {
                    this.deptList = this.handleChildren(res.responseBody);
                })
            },

            // 树形结构加载
            loadChildren: function (node, resolve) {
                console.log("树结构级别", node.level);
                if (node.level === 0) {
                    getorganization({'searchParams': {'orgCode': '-1'}}).then(res => {
                        resolve(this.handleChildren(res.responseBody));
                        this.loading = false;
                    })
                }
                if (node.level >= 1) {
                    var orgCode = node.data.orgCode;
                    console.log("====" + orgCode);
                    this.maps.set(orgCode, {node, resolve})
                    getorganization({'searchParams': {'orgCode': orgCode}}).then(res => {
                        resolve(this.handleChildren(res.responseBody));
                        this.loading = false;
                    })
                }
            },
            // 后端返回的数据对象处理，当存在子节点时显示图标
            handleChildren: function (deptList) {
                if (deptList) {
                    deptList.forEach((item, index) => {
                        if (item.attributes.count) {
                            item.hasChildren = true;
                        }
                    })
                }
                return deptList;
            },

            // 选中组织树节点
            handleNodeClick(selectedKeys) { // 选择组织树节点触发
                console.log("======== 选择组织树节点触发 ========")
                console.log("selectedKeys==" + JSON.stringify(selectedKeys));
                this.selectedTreeNodes = selectedKeys.length === 0 ? this.selectedTreeNodes : selectedKeys
                this.selectedNode = selectedKeys;
                let data = {}
                if (selectedKeys.parentId !== '-1') {
                    data = {
                        organizationId: selectedKeys.orgCode
                    };
                }
                this.userForm.orgName = selectedKeys.orgName;
                this.userForm.organizationId = selectedKeys.orgCode;
                this.getEmployeeList(data);
            },

            // 人员标签字典翻译
            getEmployeeTagFormat(row, column) {
                return this.selectDictLabel(this.getEmployeeTagOptions, row.employeeTag);
            },

            // 获取所有用户列表
            getEmployeeList(data) {
                this.loading = true
                const searchParams = {
                    searchParams: data
                };
                getEmployee(searchParams).then(res => {
                    if (res.retCode === '200') {
                        this.userList = res.responseBody
                        this.total = this.userList.length
                        this.loading = false
                        // console.log('getEmployee--,', this.userList)
                    } else {
                        console.log(res.message)
                    }
                }).catch(err => {
                    this.loading = false
                    console.log(err)
                })
            },
            /** 搜索按钮操作 */
            handleQuery() {
                if (this.selectedNode !== undefined) {
                    this.queryParams.organizationId = this.selectedNode.parentId !== '-1' ? this.selectedNode.orgCode : undefined;
                }
                this.getEmployeeList(this.addDateRange(this.queryParams, this.dateRange));
            },

            /** 重置按钮操作 */
            resetQuery() {
                this.resetForm("queryForm");
                this.dateRange = [];
                this.handleQuery();
            },

            // 多选框选中数据
            handleSelectionChange(selection) {
                this.ids = selection.map(item => item.employeeId);
                this.multiple = !selection.length;
            },
            getRowKeys(row) {
                return row.employeeId;
            },


            /** 添加用户按钮操作 */
            handleAddUser() {
                this.open = true;
                this.title = "添加用户";
            },

            /** 修改用户按钮操作 */
            handleUpdateUser(row) {
                this.userForm = row;
                this.open = true;
                this.title = "修改用户";
            },

            /** 删除用户按钮操作 */
            onDelete(row) {
                this.$confirm('确定要删除该用户吗?', "警告", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }).then(function() {
                    return deleteEmployeeTombstone(row.employeeId);
                }).then(res => {
                    if (res.retCode === '200') {
                        this.$message.success('删除成功！')
                        this.getEmployeeList({});
                    } else {
                        this.$message.error('删除失败！  错误号：' + res.retCode)
                        this.getEmployeeList({});
                        // console.log(res)
                    }
                })
            },

            /** 保存或修改用户后回调 */
            userCallBack(val) {
                this.userForm = {
                    employeeId: undefined,
                    employeeName: undefined,
                    employeeEntryTime: undefined,
                    employeeSex: undefined,
                    scheduleState: undefined,
                    employeeTelephone: undefined,
                    employeeJob: undefined,
                    organizationId: val.organizationId,
                    orgName: val.orgName,
                    employeeDutyInfo: [], // 工种
                    employeeStatusInfo: {}, //
                    // organizationId: undefined, // 部门ID
                    id: undefined,
                    employeeCertifyInfo: [] //证书
                };
                this.cancel();
            },
            // 取消按钮
            cancel() {
                this.open = false;
            },

        }
    }
</script>
